const express = require('express');
const jwt = require('jsonwebtoken');
const { secretKey } = require('./config'); // 假设你的密钥存储在 config 文件中  

const app = express();

// JWT 验证中间件  
const jwtMiddleware = (req, res, next) => {
  const token = req.headers['authorization'];

  if (!token) return res.status(401).send('Access Denied');

  jwt.verify(token, secretKey, (err, user) => {
    if (err) return res.status(500).send('Failed to authenticate token.');

    req.user = user; // 将用户信息附加到请求对象上  
    next();
  });
};

app.use(express.urlencoded({ extended: true }))
app.use(express.json()); // 允许 JSON 请求体解析

app.get('/protected-route', jwtMiddleware, (req, res) => {
  res.send(`Welcome, ${req.user.name}!`);
});

app.post('/login', (req, res) => {
  console.log(req.body)
  // 验证用户名和密码...  
  const user = { name: 'John Doe', id: 123 }; // 假设用户验证成功并获取用户信息  

  const token = jwt.sign(user, secretKey, { expiresIn: '1h' }); // 生成 JWT，1 小时后过期  

  res.json({ token }); // 将令牌发送回客户端  
});

app.post('/logout', (req, res) => {
  const log = req.body.log
  console.log(log)
  res.json({ message: 'Logout success' })
})

const PORT = process.env.PORT || 5050;

app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});